package com.ycl.blog.simplerpc;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * User: 杨成龙
 * Date: 2020/4/13
 * Time: 7:50 下午
 * Desc: 类描述
 */
public class RpcServer {

    public void export(Object service, int port) throws Exception {
        if (service == null) {
            throw new IllegalArgumentException("service instance == null");
        }
        if (port <= 0 || port > 65535) {
            throw new IllegalArgumentException("Invalid post " + port);
        }

        ServerSocket server = new ServerSocket(port);
        while (true) {
            final Socket socket = server.accept();
            new Thread(() -> {
                try {
                    ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
                    ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());

                    try {
                        String methodName = input.readUTF();//IO堵塞，获取方法名
                        Class<?>[] parameterTypes = (Class<?>[]) input.readObject();//IO堵塞，获取参数类型
                        Object[] arguments = (Object[]) input.readObject();//IO堵塞，取参数

                        //执行接口方法
                        Method method = service.getClass().getMethod(methodName, parameterTypes);
                        Object result = method.invoke(service, arguments);

                        //将结果写出去
                        output.writeObject(result);
                    } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    } finally {
                        output.close();
                        input.close();
                        socket.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }

    }

}
